package com.android.cherryboard.Task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.cherryboard.Adapters.CherryboardListAdapter;
import com.android.cherryboard.Deshboard.CherryboardListData;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.GridView;
import android.widget.ListView;

public class GetCherryboardListTask extends AsyncTask<String,Void,ArrayList<CherryboardListData>> {

	 

	private ProgressDialog progress;

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		
		 progress = ProgressDialog.show(context, 
	                null, "Loading Cherryboard List...");

	}

	GridView gridViewCherryboard;
	private Context context;
	
	public GetCherryboardListTask(GridView gridViewCherryboard) {
		super();
		this.gridViewCherryboard = gridViewCherryboard;
		this.context = gridViewCherryboard.getContext();
	}

	
	
	@Override
	protected void onPostExecute(ArrayList<CherryboardListData> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		progress.dismiss();
		CherryboardListAdapter adapter = new CherryboardListAdapter(gridViewCherryboard.getContext(),result);
		gridViewCherryboard.setAdapter(adapter);
		 
		
		
	}

	@Override
	protected ArrayList<CherryboardListData> doInBackground(String... params) {
		// TODO Auto-generated method stub
		JSONArray jsonArray = getJSONArrayFromURL(params[0]);
		ArrayList<CherryboardListData> cherryboardListDatas = parserJsonArray(jsonArray);
		
		
		return cherryboardListDatas ;
	}

	private ArrayList<CherryboardListData>  parserJsonArray(JSONArray jsonArray) {
		// TODO Auto-generated method stub
		
		ArrayList<CherryboardListData> cherryboardListDatas = new ArrayList<CherryboardListData>();
		cherryboardListDatas.clear();
		
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				
				CherryboardListData cherryboardListData = new CherryboardListData();
				cherryboardListData.setCherryboard_id(jsonObject.getString("cherryboard_id"));
				cherryboardListData.setCherryboard_title(jsonObject.getString("cherryboard_title"));
				cherryboardListDatas.add(cherryboardListData);
				 
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			cherryboardListDatas.clear();
			
		}
		return  cherryboardListDatas;
		
	}

	private JSONArray getJSONArrayFromURL(String url){
		   InputStream mIs = null;
	        String result = "";
	        JSONArray jArrayEvent = null;
	        try {
	            HttpClient httpclient = new DefaultHttpClient();
	            HttpPost httppost = new HttpPost(url);
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity entity = response.getEntity();
	            mIs = entity.getContent();
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        
	        try{
	            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(mIs,"iso-8859-1"),8);
	            StringBuilder stringBuilder = new StringBuilder();
	            String line = null;
	            while ((line = bufferReader.readLine()) != null) {
	                if(line.trim().equals("\n"))
	                    continue;
	                stringBuilder.append(line + "\n");
	            }
	            mIs.close();
	            result=stringBuilder.toString();
	        }catch(Exception e){
	            
	            Log.e("log_tag", "Error converting result "+e.toString());
	        }
	        try {
	        	JSONObject jsonObject = new JSONObject(result);
	        	jArrayEvent = jsonObject.getJSONArray("data");
	        	jArrayEvent = new JSONArray(result);
	        } catch (JSONException e) {
	            
	            e.printStackTrace();
	        }

	        return jArrayEvent;
	}
}
